# coding=utf-8

from django.utils import importlib
import re
from django.core.management import BaseCommand
import sys
from article.management import SyncHook, get_logger
from article.models import Category

logger = get_logger()

slug_re = re.compile(r',\s，。《》“\"\'')


class Command(BaseCommand):
    def handle(self, *args, **options):
        logger.info('开始')

        for category in Category.objects.all():
            if not category.sync_sources.exists():
                logger.info(u'忽略%s' % category.title)
                continue
            for src in category.sync_sources.all():
                logger.info(u'开始同步%s。同步程序：%s。源地址:%s\n' % (category.title, src.sync_hook, src.sync_source))

                i = src.sync_hook.rfind('.')
                module, sync_cls = src.sync_hook[:i], src.sync_hook[i + 1:]
                module = importlib.import_module(module)
                sync_cls = getattr(module, sync_cls)
                syncer = sync_cls()
                if not isinstance(syncer, SyncHook):
                    logger.error(u'同步程序不是SyncHook的子类')
                else:
                    syncer.sync(category, src)

        logger.info('结束')